#include "YMagnifier.h"
#include <QApplication>
#include <QScreen>
#include <QPainter>
#include <QKeyEvent>
#include <QDebug>

YMagnifier::YMagnifier(QImage *pixmap) : QWidget(nullptr), pImage(pixmap), map(QImage(120, 120, QImage::Format_RGB888))
{
    threshold = qApp->primaryScreen()->size() - QSize(145, 145);

//    setFixedSize(120, 120);
    setFixedSize(120, 120 + 70);
    setWindowFlags(Qt::ToolTip | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
}

void YMagnifier::setImage(const QImage &image)
{
    this->image = image;
}

void YMagnifier::set(const QPoint &pos)
{
    if(pos == point) return;
    point = pos;
    rePos();

    QImage realImage = (pImage ? *pImage : image), partImage(30, 30, QImage::Format_RGB888);
    for(int x = pos.x() - 15, row = 0; row < 30; ++x, ++row){
        for(int y = pos.y() - 15, col = 0; col < 30; ++y, ++col){
            if(x < 0 || y < 0 || x >= realImage.width() || y >= realImage.height()){
                partImage.setPixel(row, col, Qt::black);
            }else{
                partImage.setPixel(row, col, realImage.pixel(x, y));
            }
        }
    }
    create(partImage);

    if(isHidden()) show();
    raise();
}

void YMagnifier::unset()
{
    if(!isHidden()) {
        hide();
        point = QPoint(-1, -1);
    }
}

void YMagnifier::rePos()
{
    QPoint pos = QCursor::pos();
    move((pos.x() > threshold.width() ? pos.x() - 122 : pos.x() + 22), (pos.y() > threshold.height() ? pos.y() - 122 : pos.y() + 22));
}

#define RATIO 4
void YMagnifier::create(const QImage &part)
{
    if(part.width() > 30 || part.height() > 30) return;
    for(int x = 0; x < part.width(); ++x){
        int rx = x * RATIO;
        for(int y = 0; y < part.height(); ++y){
            int ry = y * RATIO;
            for(int row = 0; row < RATIO; ++row){
                int rrow = rx + row;
                for(int col = 0; col < RATIO; ++col){
                    map.setPixel(rrow, ry + col, part.pixel(x, y));
                }
            }
        }
    }
    update();
}

void YMagnifier::setRatio(int ratio)
{
    if(this->ratio != ratio){
        this->ratio = ratio;
    }
}

void YMagnifier::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    p.drawImage(0, 0, map);

    p.setBrush(QColor(33, 33, 33));
    p.drawRect(0, 121, 120, 70);
    p.setBrush(Qt::NoBrush);

    p.setPen(QPen(QBrush(QColor(127,255,255, 150)), 5));
    p.drawLine(0, 61, 119, 61);
    p.drawLine(61, 0, 61, 119);

    p.setPen(Qt::white);
    QImage ri = (pImage ? *pImage : image);
    currentColor = ri.pixelColor(point);
    p.drawText(QRect(2, 127, 118, 63), QString("长宽:(%1x%2)\n鼠标:(%3,%4)\nRGB:(%5,%6,%7)\n按C复制RGB")
               .arg(ri.width()).arg(ri.height())
               .arg(point.x()).arg(point.y())
               .arg(currentColor.red()).arg(currentColor.green()).arg(currentColor.blue()) );
}

void YMagnifier::keyReleaseEvent(QKeyEvent *keyEvent)
{
    emit keyClicked(Qt::Key(keyEvent->key()));
}












